package com.ifast.common.utils;

import com.ifast.api.util.JWTUtil;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class ShiroUtils {
	public static Subject getSubjct() {
		return SecurityUtils.getSubject();
	}
	
	// api
//	private final static AppUserDao appUserDao = SpringContextHolder.getBean(AppUserDao.class);
//	public static AppUserDO getAppUserDO() {
//	    String jwt = (String)getSubjct().getPrincipal();
//	    String userId = JWTUtil.getUserId(jwt);
//	    return appUserDao.selectById(userId);
//	}
	
	// admin
	/*public static UserDO getSysUser() {
		return (UserDO)getSubjct().getPrincipal();
	}*/
	/*public static Long getUserId() {
		return getSysUser().getId();
	}*/
	
	public static void logout() {
		getSubjct().logout();
	}


	public static UserDO getSysUser() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Object principal = subject.getPrincipal();
			if(principal instanceof String){
				String token = (String)principal;
				String userId = JWTUtil.getUserId(token);
				UserDO userDO = SpringContextHolder.getBean(UserService.class).getById(userId);
				return userDO;
			}else if(principal instanceof UserDO) {
				return (UserDO)principal;
			}
		}catch (Exception ignore) { }
		return null;
	}

	public static Long getUserId() {
		UserDO sysUser = getSysUser();
		return sysUser == null ? null : sysUser.getId();
	}
}
